package com.breeze.breezelive;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Size;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;

import com.breeze.breezelive.record.LiveManager;
import com.breeze.breezelive.utils.ImageUtil;
import com.google.common.util.concurrent.ListenableFuture;

import java.io.File;
import java.util.concurrent.ExecutionException;

public class LiveActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private PreviewView previewView;
    private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
    private Handler analysisHandler;
    private HandlerThread handlerThread;
    private LiveManager liveManager;
    private int width, height;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live);
        previewView = findViewById(R.id.previewView);
        cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                bindPreview(cameraProvider);
            } catch (ExecutionException | InterruptedException e) {
                // No errors need to be handled for this Future.
                // This should never be reached.
            }
        }, ContextCompat.getMainExecutor(this));

        liveManager = LiveManager.getInstance();
        handlerThread = new HandlerThread("image-analysis");
        handlerThread.start();
        analysisHandler = new Handler(handlerThread.getLooper());
    }

    void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
        Preview preview = new Preview.Builder()
                .setTargetResolution(new Size(640, 480))
                .build();
        CameraSelector cameraSelector = new CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_FRONT)
                .build();
        preview.setSurfaceProvider(previewView.getSurfaceProvider());
        ImageAnalysis imageAnalysis =
                new ImageAnalysis.Builder()
                        .setTargetResolution(new Size(640, 480))
                        .build();
        imageAnalysis.setAnalyzer(new HandlerExecutor(analysisHandler), image -> {
            int rotationDegrees = image.getImageInfo().getRotationDegrees();
            byte[] bytes = ImageUtil.getBytes(image, rotationDegrees);
            liveManager.frame(bytes);
            width = image.getWidth();
            height = image.getHeight();
            image.close();
        });
        cameraProvider.bindToLifecycle(this, cameraSelector, imageAnalysis, preview);
    }

    public void startLive(View view) {
        liveManager.prepare(new File(getExternalFilesDir("temp"), "abc.mp4").getAbsolutePath());
        liveManager.start(width, height);
    }

    public void stopLive(View view) {
        liveManager.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handlerThread.quitSafely();
        liveManager.release();
    }
}